from flask import Blueprint, render_template, request, redirect, url_for, flash,session,jsonify
from exts import db
# from .forms import RegisterForm, LoginForm
from models import UserModel
import re

# 登录注册功能

bp = Blueprint("auth", __name__, url_prefix="/auth")

# 跳转到注册页面
@bp.route("/register")
def register1():
    return render_template("Login/register.html")

# 登录验证
@bp.route("/login1",methods=['POST'])
def login1():
    # 获得前端传递参数
    useranme=request.form["userName"]
    pwd=request.form['pwd']
    user=UserModel.query.filter_by(userid=useranme).first()
    # 判断
    if user:
        if user.userpassword==pwd:
            session['user_id'] = user.userid
            return jsonify({'state':'200'})
        else:
            return jsonify({'state':'300','msg':'密码不正确！'})
    else:
        return jsonify({'state':'400','msg':"用户不存在！"})

# 验证手机号码
def is_valid_phone_number(phone_number):
    pattern = r'^1[3456789]\d{9}$'
    return bool(re.match(pattern, phone_number))

# 验证邮件
def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

# 验证密码
def is_valid_password(password):
    pattern=r'^(?=.*[a-zA-Z])(?=.*\d)\w{6,}$'
    return bool(re.match(pattern,password))

# 注册验证
@bp.route("/register2",methods=['POST','GET'])
def register2():
    # 获得前端传递参数
    userid=request.form['userid']
    username=request.form['username']
    phone=request.form['phone']
    email=request.form['email']
    password1=request.form['password1']
    password2=request.form['password2']
    user = UserModel.query.filter_by(userid=userid).first()
    # 验证
    if user:
        return jsonify({'state':'400','msg':'用户已经存在！'})
    else:
        if is_valid_phone_number(phone):
            if is_valid_email(email):
                if is_valid_password(password1):
                    if password1==password2:
                        user = UserModel(userid=userid, username=username, useremail=email, userphone=phone,userpassword=password1)
                        db.session.add(user)
                        db.session.commit()
                        return jsonify({'state':'200','msg':'注册成功！'})
                    else:
                        return jsonify({'state': '400', 'msg': '两次密码输入不一致！'})
                else:
                    return jsonify({'state': '400', 'msg': '密码格式不正确！'})
            else:
                return jsonify({'state': '400', 'msg': '邮箱不正确！'})
        else:
            return jsonify({'state': '400', 'msg': '手机号码不正确！'})